# Maintainer: Alexey Pavlov <alexpux@gmail.com>

_realname=jxrlib
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=1.1
pkgrel=3
pkgdesc="Open source implementation of jpegxr (mingw-w64)"
arch=('any')
url="https://jxrlib.codeplex.com/"
license=('BSD')
validpgpkeys=('gpg_KEY')
makedepends=("${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-gcc"
             "${MINGW_PACKAGE_PREFIX}-iconv")
depends=("${MINGW_PACKAGE_PREFIX}-gcc-libs")
options=('strip' 'staticlibs')
source=(${_realname}-${pkgver}.tar.gz::"https://launchpad.net/ubuntu/+archive/primary/+files/jxrlib_${pkgver}.orig.tar.gz"
        "CMakeLists.txt"
        "jxrlib_warnings.patch"
        "jxrlib_mingw.patch"
        "bug748590.patch")
sha256sums=('c7287b86780befa0914f2eeb8be2ac83e672ebd4bd16dc5574a36a59d9708303'
            '68c51480b3aab38edec4a62aad9e57e7f86bd32aeb7fb89bead151ebad0f1661'
            'be85117d2f0af1f0edc2389c9379198d2b69f00ab1d036911a8436cd3abbe96e'
            'aa0cd3b0c9c96876e8d7d204cd3b240d91864a54de82fb83db3e094a1cf03302'
            '7dd68177ccfd6650dad87d8030349de228f740efde54d34b9fb54426e31d0d83')

prepare() {
  cd "${srcdir}/${_realname}-${pkgver}"
  
  # Sanitize charset and line endings
  for file in $(find . -type f \( -name '*.c' -or -name '*.h' -or -name '*.txt' \) ); do
    ${MINGW_PREFIX}/bin/iconv -f ISO-8859-15 -t UTF-8 ${file} > ${file}.new && \
        sed -i 's|\r||g' ${file}.new && \
        touch -r ${file} ${file}.new && mv ${file}.new ${file}
  done
  
  # Remove file which already exists as part of the mingw headers
  rm -f common/include/guiddef.h
  
  cp -f "${srcdir}/CMakeLists.txt" .
  
  patch -p1 -i "${srcdir}/jxrlib_warnings.patch"
  patch -p1 -i "${srcdir}/jxrlib_mingw.patch"
  patch -p1 -i "${srcdir}/bug748590.patch"
}

build() {
  [[ -d "${srcdir}/build-${CARCH}" ]] && rm -rf "${srcdir}/build-${CARCH}"
  mkdir -p "${srcdir}/build-${CARCH}" && cd "${srcdir}/build-${CARCH}"
 
  declare -a extra_config
  if check_option "debug" "n"; then
    extra_config+=("-DCMAKE_BUILD_TYPE=Release")
  else
    extra_config+=("-DCMAKE_BUILD_TYPE=Debug")
  fi

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
    ${MINGW_PREFIX}/bin/cmake \
      -G'MSYS Makefiles' \
      -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
      "${extra_config[@]}" \
      ../${_realname}-${pkgver}

  make
}

package() {
  cd "${srcdir}/build-${CARCH}"
  make DESTDIR="${pkgdir}" install
}
